from typing import Type
from domain.charMeta import role_reverse
from role_play_core.playGenerator import PlayGenerator
from role_play_core.roleDesigner import RoleDesigner
from role_play_core.topicStarter import TopicStarter
from role_play_core.writer import Writer
from utils.msgToFileWriter import MsgToFileWriter
from utils.helloTopicStarter import HelloTopicStarter

class RolePlay:
    def __init__(self, role1_desc: str, role2_desc: str, topic_starter:Type[TopicStarter] = HelloTopicStarter, verbose: bool = False):
        role_designer = RoleDesigner(verbose=verbose)
        self.agent1 = PlayGenerator(re := role_designer.invoke(role1_desc, role2_desc))
        self.agent2 = PlayGenerator(role_reverse(re))
        self.topic_starter = topic_starter(role2_desc, role1_desc)

    def invoke(self, loop: int = 3):
        speak_message = self.topic_starter.invoke()
        self.agent2.messages.append({'role': 'assistant', 'content': speak_message})
        for _ in range(loop):
            message = self.agent1.invoke(speak_message).content
            speak_message = self.agent2.invoke(message).content

    def save(self, writer: Writer = MsgToFileWriter()):
        data = [{'role': d['role'], 'content': f"{self.agent2.name if i % 2 == 0 else self.agent1.name}: {d['content']}"}
                for i, d in enumerate(self.agent2.messages)]
        writer.write(data)

